package com.shiro.sso.demo.utils;

import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class SsoLoginStore {

    public static long timeout = 5 * 60 * 1000;//5分钟

    private static RedisTemplate redisTemplate;

    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        SsoLoginStore.redisTemplate = redisTemplate;
    }

    public static RedisTemplate getRedisTemplate() {
        return SsoLoginStore.redisTemplate;
    }

    public static Session get(String sessionId) {
        String redisKey = redisKey(sessionId);
        Object objectValue = getRedisTemplate().opsForValue().get(redisKey);
        return SerializableUtil.deserialize(objectValue);
    }

    public static void remove(String sessionId) {
        String redisKey = redisKey(sessionId);
        getRedisTemplate().delete(redisKey);
    }

    public static void put(String sessionId, Session session) {
        String redisKey = redisKey(sessionId);
        getRedisTemplate().opsForValue()
                .set(redisKey, SerializableUtil.serialize(session), timeout, TimeUnit.MILLISECONDS);
    }

    private static String redisKey(String sessionId) {
        return Constant.SESSION_PREFFIX.concat(sessionId);
    }

}
